const db = require("../models");
const logger = require("../utils/utils.logger");
const DAO = require("../dao/DAO");
const {sendMailer} = require("../utils/utils.nodemailer");
const ChatMessage = db.message;

// Create and Save a new ChatMessage
exports.create = (req, res) => {
    const pm = req.body;
    // 请求验证
    if (!pm.email) return res.sendResult({data: '', code: 605, message: "留言邮箱不能为空！"})
    if (!pm.content) return res.sendResult({data: '', code: 605, message: "留言描述不能为空！"})
    // Create a ChatMessage
    const newMessage = {
        email: pm.email,
        status: false,
        content: pm.content,
    };
    DAO.create(ChatMessage, newMessage, data => {

        res.sendResult(data)
        //留言成功后 发送言邮件通知
        // let p = {
        //     email: '1840354092@qq.com',
        //     content: `您收到了一份留言：${pm.content},-----快去查看`
        // }
        // sendMailer(p).then(info => {
        //     res.sendResult(data)
        // })
    })
};

// Retrieve all ChatMessage from the database.
exports.findAll = (req, res) => {
    const pm = req.body;
    DAO.list(ChatMessage, pm, list => {
        res.sendResult(list)
    })
};

// Find a single ChatMessage with an id
exports.findOne = (req, res) => {
    const pm = req.body;
    DAO.findOne(ChatMessage, pm, data => {
        res.sendResult(data)
    })
};

// Update a ChatMessage by the id in the request
exports.update = (req, res) => {
    const pm = req.body;
    // 请求验证
    if (!pm.id) return res.sendResult({data: '', code: 605, message: "ID不能为空！"})
    DAO.update(ChatMessage, pm, {id: pm.id}, data => {
        logger.debug(`${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(pm)}; 响应：${JSON.stringify(data)}`);
        res.sendResult(data)
    })

};

// Delete a ChatMessage with the specified id in the request
exports.delete = (req, res) => {
    const pm = req.body;
    // 请求验证
    if (!pm.id) return res.sendResult({data: '', code: 605, message: "ID不能为空！"})
    DAO.delete(ChatMessage, {id: pm.id}, data => {
        logger.debug(`${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(pm)}; 响应：${JSON.stringify(data)}`);
        res.sendResult(data)
    })
};

// 回复留言
exports.replyMsg = (req, res) => {
    const pm = req.body;
    ChatMessage.update({status: true}, {
        where: {
            id: pm.id
        }
    }).then(_info => {
        res.status(200).sendResultAto(_info, 200, '回复成功！')
    }).catch(err => {
        console.log("err:",err)
        res.status(500).sendResultAto(err, 605, '回复失败！')
    })
   //  邮箱回复
   /* sendMailer({email: pm.email, content: pm.content}).then(info => {
        //去修改状态
        // pm.status = true
        ChatMessage.update({status: true}, {
            where: {
                id: pm.id
            }
        }).then(_info => {
            res.status(200).sendResultAto(info, 200, '回复成功！')
        })
    }).catch(err => {
        console.log("err:",err)
        res.status(500).sendResultAto(err, 605, '回复失败！')
    })*/

};

